import { defineStore } from "pinia";
import { getToken, setToken, getUser, setUser,removeToken,removeUser } from "@/utils/auth"
import { encrypt } from "@/utils/encrypt"
import { register, loginApi, getUserInfo } from "@/api/login"

const useUserStore = defineStore('user', {
    state: () => ({
        token: getToken(),
        user: getUser(),
        loading: false,
    }),
    actions: {
        //登录的逻辑请求信息
        async login(data) {
            let params = {
                username: data.username,
                password: encrypt(data.password)
            }

            let res = await loginApi(params);

            if (res.code === 200) {
                let token = res.data.token;
                setToken(token);
                this.token = res.data.token;
                //请求获取用户信息的接口，存储用户信息
                let ret = await getUserInfo();
                //获取用户信息成功后
                if (ret.code === 200) {
                    setUser(ret.data);
                    this.user = ret.data;
                    this.loading = false;
                    return res;
                }else{
                    this.loading = false;
                    return ret;
                }
            }else{
                return res;
            }
        },
        //请求注册的方法，数据存储在pinia中
        async register(data) {
            let params = {
                username: data.username,
                password: encrypt(data.password),
            }

            let res = await register(params);
            this.loading = false;
            return res;
        },

        //请求获取用户详情信息内容
        async getUser(){
            //请求获取用户信息的接口，存储用户信息
            let ret = await getUserInfo();
            //获取用户信息成功后
            if (ret.code === 200) {
                setUser(ret.data);
                this.user = ret.data;
            }
            return ret;
        },
        async logout(){
            removeToken();
            removeUser();
            return {code:200,msg:"success"};
        }
    }
})

export default useUserStore;